package com.chart.web.controller.openfeign;

import com.chart.common.core.domain.model.LoginBody;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class FeignAuthRequestInterceptor implements RequestInterceptor {

    @Autowired
    private ExternalServiceClient externalServiceClient;

    private String token;
    private boolean isLoggingIn = false; // 标志位，防止递归调用

    @Override
    public void apply(RequestTemplate requestTemplate) {
        if (token != null && !token.isEmpty()) {
            requestTemplate.header("Authorization", "Bearer " + token);
        } else if (!isLoggingIn) {
            isLoggingIn = true; // 设置标志位
            try {
                token = loginAndGetToken(); // 获取新的 token
                requestTemplate.header("Authorization", "Bearer " + token);
            } finally {
                isLoggingIn = false; // 确保在请求完成后重置标志
            }
        }
    }

    private String loginAndGetToken() {
        LoginBody loginBody = new LoginBody();
        loginBody.setUsername("admin"); // 根据实际情况设置用户名
        loginBody.setPassword("123456"); // 根据实际情况设置密码

        String loginResponse = externalServiceClient.login(loginBody);
        return parseTokenFromResponse(loginResponse);
    }

    private String parseTokenFromResponse(String response) {
        try {
            JsonNode rootNode = new ObjectMapper().readTree(response);
            return rootNode.path("token").asText();
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse token from response", e);
        }
    }
}
